package com.ztn.sdk.iot.hook;

import com.rabbitmq.client.*;
import com.ztn.sdk.iot.api.util.JsonTool;
import com.ztn.sdk.iot.hook.bean.IotSystemHookWarp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class HookTool {

    private final static Logger log = LoggerFactory.getLogger(HookTool.class);

    public static String URL = "iot.mq.rabbit.ztn-tech.com";
    public static int PORT = 5672;
    public static String USER_NAME = "test";
    public static String PASSWORD = "Ztn654321";
    public static String EXCHANGE_NAME = "ztn.iot.sdk";
    public static String QUEUE_BASE_NAME = EXCHANGE_NAME + ".";
    public static boolean IS_DURABLE = true;


    public void connect(String topic, IMsgHandler msgHandler) throws IOException, TimeoutException {
        String queueName = QUEUE_BASE_NAME + topic;
        log.info("rabbit try connect {}", URL);

        final String[] urlSplit = URL.split(":");

        String host = null;
        if (urlSplit.length == 2) {
            host = urlSplit[0];
            PORT = Integer.parseInt(urlSplit[1]);
        } else if (urlSplit.length == 1) {
            host = urlSplit[0];
        } else {
            log.error("unKnow url {}", URL);
        }
        log.info("rabbit host:{} port:{} userName:{} password:{}", host, PORT, USER_NAME, PASSWORD);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(PORT);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        final Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "topic", true, false, null);
        channel.queueDeclare(queueName, IS_DURABLE, false, !IS_DURABLE, null);
        channel.queueBind(queueName, EXCHANGE_NAME, topic);
        // 创建队列消费者
        final Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                msgHandler.handler(topic, JsonTool.fromJson(message, IotSystemHookWarp.class));
            }
        };
        channel.basicConsume(queueName, true, consumer);


    }


}
